// /**
//  * 
//  * @authors Your Name (you@example.org)
//  * @date    2017-12-28 14:05:33
//  * @version $Id$
//  */

window.onload=function(){
//		var timer=setInterval(function(){
			if (localStorage.userToken) {
				creatshop()
//				clearInterval(timer)
			}
//		},1000)
	}
/*购物车基础数据渲染*/
function creatshop(){
		mui.ajax({
		"url":URL_all+"client/detailed/selectbyuserId?page=10&pagesize=20&adcode=100000",
		"dataType":"json",
		"type":"get",
		"timeout":10000000000,
		"headers":{'userToken':localStorage.userToken},
		"success":function(data){
			console.log(localStorage.userToken)
			console.log(data)
			$(".promain").empty();
			var shopping = '';
			$.each(data.pageInfo.list,function(index,oneItem){
				if(oneItem.commodityNumber!=""&&oneItem.commodityNumber!=null){
					if(oneItem.dataResultObj!=null){
				console.log(oneItem.commodityNumber)
					if(oneItem.dataResultObj.Sqlstatus == 'Error-商品不存在或已经下架子'){
						
					}else{
						shopping += '<div class="product">'+
							'<div class="product_checked show">'+
								'<div class="checked product_checked_unchecked asdf">'+
//									'<input type="checkbox" name="fruit" class="asdf" value="" >'+
								'</div>'+
							'</div>'+
							'<div class="product_checked del" style="display:none" id='+oneItem.commodityNumber+'><div class="checked product_checked_del" ></div></div>'+
							'<div class="product_parameter ProductDetailHref">'+
								'<div class="product_parameter_info">'+
									'<div class="product_parameter_info_pic"><div></div></div>'+
									'<div class="product_parameter_info_info1">'+
										'<div class="product_name product_font">'+oneItem.dataResultObj.title+'</div>'+
										'<div class="product_Specifications product_font">规格：1.22米×2.44米×9厘/18厘</div>'+
										'<div class="product_Distribution product_font">自主配送</div>'+
									'</div>'+
									'<div class="product_parameter_info_info2">'+
										'<div class="product_Price">￥<span>'+ parseFloat(oneItem.dataResultObj.presentPrice/100).toFixed(2)+'</span></div>'+
										'<div class="product_Number">×<span>'+oneItem.needNumber+'</span></div>'+
									'</div>'+
								'</div>'+
								'<div class="product_parameter_Stock">库存：120张</div>'+
							'</div>'+
						'</div>'
					}
				
				
			
		}
	}
			})
			$(".promain").html(shopping)
			dji()
// +oneItem.dataResultObj[index].presentPrice+
		},
		"error":function(xhr,type,errorThrown){
			console.log(type);
		}
	})
}

/*立即购买*/
function GoToBuyListener(){
	document.getElementById('gotobuy').addEventListener('click',function(){
		var result = [];//购物清单
        // var checkedCommodityNumber = orderCount.checkedCommodityNumber;
		for(var i=0;i<$(".product_checked_Selected.asdf").length;i++){//添加购物清单
				var domId = $(".product_checked_Selected.asdf").eq(i);
				var commodityNumber = domId.parents(".product").find(".del").attr("id");
				var count = domId.parents(".product").find(".product_Number span").text();
				// var curProductElem = mui("#"+domId)[0];
				// var commodityNumber = curProductElem.getAttribute("title");
				// var count = curProductElem.getAttribute("num");
				// 
				// $(".asdf:checked").eq(0).parents(".product").find(".del").attr("id")
				// 
				result.push(
					{
						'commodityNumber':commodityNumber,
						'count':count
					}
				);
		}
		if(result.length>0){//当购物清单长度大于0，即可进入“确认订单”页面
			result["present"] = false;
			result = JSON.stringify(result);//转化为字符串
			console.log("转换成功！"+result);
			localStorage.setItem('goodsList',result);
			window.location.href = "order_confirm.html";
		}
	})
}


//点击编辑按钮
	$("#edit").click(function(){
		if($(".del")[0].style.display=="none"){
			$(".del").show()

			for(var i=0;i<$(".del").length;i++){
				(function(i){
					$(".del").eq(i).click(function(){
						var  commodityNumber = ($(this).attr("id"));
						var btnArray = ['不，我还需要', '删除'];
						mui.confirm('', '确定要删除该商品吗', btnArray, function(e) {
							if (e.index == 1) {
								console.log(commodityNumber)
									mui.ajax({
										"url":URL_all+"client/detailed/deletebycommodity",
										"data":"{'commodityNumber':'"+commodityNumber+"'}",
										"dataType":"json",
										"type":"post",
										"timeout":10000000000,
										"headers":{'userToken':localStorage.userToken,'Content-Type':'application/json'},
										"success":function(data){
											
											console.log(localStorage.userToken)
											console.log(JSON.stringify(data))
											mui.toast("删除成功！")
										},
										"error":function(xhr,type,errorThrown){
											console.log(type);
										}
									})							
							} else {
								// info.innerText = 'MUI没有得到你的认可，继续加油'
							}
						})					
					})
				})
				(i)}
			$(".show").hide()
		}else{
			$(".show").show()
			$(".del").hide()
		}
		
	})

/*点击按钮选中商品*/
function dji(){
	//点击单选按钮
	$(".asdf").on("tap",function(){
		if($(".asdf").hasClass('product_checked_Selected')){
    		$(".asdf").removeClass('product_checked_Selected').addClass('product_checked_unchecked'); 
    		jisuan()
		}else if($(".asdf").hasClass('product_checked_unchecked')){
			$(".asdf").removeClass('product_checked_unchecked').addClass('product_checked_Selected');
			jisuan()
		}
		
		//dnp
		
		if(mui(".asdf.product_checked_unchecked").length==0){
			$('#Select').removeClass('product_checked_unchecked').addClass('product_checked_Selected');
			jisuan1();
		}else{
			$("#Select").removeClass('product_checked_Selected').addClass('product_checked_unchecked');
		}
		
	})
//点击全选按钮
    $('#Select').on("tap",function(){
    	if( $('#Select').hasClass('product_checked_Selected')){
//  		for(var i=0;i<$(".asdf").length;i++){
//	    		$(".asdf")[i].checked=false;
//	    	}
			document.getElementById("TotalAmount").innerText = "0"; 
			document.getElementsByClassName("bottom_number")[0].innerHTML = ""
	    	$('#Select').removeClass('product_checked_Selected').addClass('product_checked_unchecked');
	        $(".asdf").removeClass('product_checked_Selected').addClass('product_checked_unchecked');
	    }else{
//	    	for(var i=0;i<$(".asdf").length;i++){
//	    		$(".asdf")[i].checked=true;
//	    	}
	    	jisuan1()
	    	document.getElementsByClassName("bottom_number")[0].innerHTML = "(" + $(".asdf").length + ")"
	    	$('#Select').removeClass('product_checked_unchecked').addClass('product_checked_Selected');
	        $(".asdf").removeClass('product_checked_unchecked').addClass('product_checked_Selected');
	    }
	    //dnp
//	    if(mui("#Select.product_checked_unchecked").length==0){
//	    	$('.checked').removeClass('product_checked_unchecked').addClass('product_checked_Selected');
//			jisuan1();
//		}else{
//			$(".checked").removeClass('product_checked_Selected').addClass('product_checked_unchecked');
//		}
	})
}

/*计算单个商品的价格*/
function jisuan(){
	var total = 0; 
	var sad = 0; 
	var sv=0;
	var fruits = document.getElementsByName("fruit"); 
	$(".asdf").each(function(){
		if($(this).parents(".checked").hasClass('product_checked_Selected')){
			var num = parseInt($(this).parents(".product").find(".product_Number span").text())
			var price = parseInt($(this).parents(".product").find(".product_Price span").text())
			var total = price * num;
			sv += total;
			sad++;
		}
	})
	if(sad=="0"){
		document.getElementsByClassName("bottom_number")[0].innerHTML = ""
	}else{
		document.getElementsByClassName("bottom_number")[0].innerHTML = "（" + sad + "）"
	}
	$("#TotalAmount").text(sv)
} 

/*计算所有商品的价格*/
function jisuan1(){
	var total = 0; 
	var sad = 0; 
	var sv=0;
	var fruits = document.getElementsByName("fruit"); 
	$(".asdf").each(function(){
		var num = parseInt($(this).parents(".product").find(".product_Number span").text())
		var price = parseInt($(this).parents(".product").find(".product_Price span").text())
		var total = price * num;
		sv += total;
		sad++;
	})
	if(sad=="0"){
		document.getElementsByClassName("bottom_number")[0].innerHTML = ""
	}else{
		document.getElementsByClassName("bottom_number")[0].innerHTML = "（" + sad + "）"
	}
	$("#TotalAmount").text(sv)
} 

/*结算按钮*/    

$(".orderConfirmHref").on("tap",function(){
	if($(".bottom_number").text().length>0){
		GoToBuyListener()
		// OpenNewWindow("order_confirm.html","order_confirm.html",{},{},{});
	}else{
		mui.toast("您还没有选择商品")
	}
})	